let requestData = {
    pagenum: 1,
    pagesize: 3,
    cate_id: '',
    state: ''
}

let layer = layui.layer
let form = layui.form
let laypage = layui.laypage
initTable()
initCate()

function initTable() {
    $.ajax({
        method: 'GET',
        url: '/my/article/list',
        data: requestData,
        success: function (res) {
            console.log(res);
            if (res.status !== 0) {
                return layer.msg('获取文章列表失败！')
            }
            $('tbody').html(template('tpl-table', res.data))
            renderPage(res.total)
        }
    })
}

template.defaults.imports.dataFormat = function (date) {
    const dt = new Date(date)
    let y = dt.getFullYear()
    let m = dt.getMonth() + 1
    let d = dt.getDate()
    let hh = padZero(dt.getHours())
    let mm = padZero(dt.getMinutes())
    let ss = padZero(dt.getSeconds())
    return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}

$('#form-search').submit(function (e) {
    e.preventDefault()
    let cate_id = $('select[name="cate_id"]').val()
    let state = $('select[name="state"]').val()
    requestData.cate_id = cate_id
    requestData.state = state
    initTable()
})

$('tbody').on('click', '#btn-delete', function () {
    let id = $('#btn-delete').attr('data-id')
    let len = $('#btn-delete').length
    layer.confirm('确认删除?', { icon: 3, title: '提示' }, function (index) {
        //do something
        $.ajax({
            method: 'GET',
            url: `/my/article/delete/${id}`,
            success: function (res) {
                if (res.state !== 0) {
                    return layer.msg('删除文章失败！')
                }
                layer.msg('删除文章成功！')
                if (len === 1) {
                    requestData.pagenum = requestData.pagenum === 1 ? 1 : requestData.pagenum - 1
                }
                initTable()
            }
        })
        layer.close(index);
    });
})

function padZero(date) {
    return date > 9 ? data : '0' + data
}

function initCate() {
    $.ajax({
        method: 'GET',
        url: '/my/article/cates',
        success: function (res) {
            console.log(res);
            if (res.status !== 0) {
                return layer.msg('获取分类数据失败！')
            }
            $('select[name="cate_id"]').html(template('tpl-cate', res))
            form.render()
        }
    })
}

function renderPage(total) {
    console.log(total);
    laypage.render({
        elem: 'pageBox',
        count: total,
        limit: requestData.pagesize,
        limits: [2, 3, 5, 10],
        curr: requestData.pagenum,
        jump: function (obj, first) {
            requestData.pagenum = obj.curr
            requestData.pagesize = obj.limit
            if (!first) {
                initTable()
            }
        },
        layout: ['count', 'limit', 'prev', 'page', 'next', 'skip']
    })
}